package baiqitun.stupro.project.core.process.impl;

import baiqitun.stupro.common.exception.enums.support.StuproExceptionEnum;
import baiqitun.stupro.common.exception.StuproException;
import baiqitun.stupro.common.workflow.enums.ProcessDefinitionKeyEnum;
import baiqitun.stupro.common.workflow.enums.ProcessVariableEnum;
import baiqitun.stupro.common.workflow.util.RuntimeTaskUtil;
import baiqitun.stupro.project.constant.ProjectProcessVariableEnum;
import baiqitun.stupro.project.core.document.entity.SysProjectDocument;
import baiqitun.stupro.project.core.process.CreateSubjectProjectProcess;
import baiqitun.stupro.project.entity.SysProject;
import baiqitun.stupro.security.entity.SysUser;
import baiqitun.stupro.security.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

/**
 * @author kedaji
 */
@Service
public class CreateSubjectProjectProcessImpl implements CreateSubjectProjectProcess {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RuntimeTaskUtil runtimeTaskUtil;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void sendRequest(SysProject project, SysProjectDocument document) {
        if (project.getCreateBy() == null){
            throw new StuproException(StuproExceptionEnum.PARAMETER_CANNOT_NULL).put(SysProject.class, "createBy",null);
        }
        SysUser root = sysUserService.getUserByUsername("root");
        SysUser user = sysUserService.getEnabledUser(project.getCreateBy());
        HashMap<String,Object> variables = new HashMap<>();
        variables.put(ProcessVariableEnum.NAME.name(), project.getName());
        variables.put(ProcessVariableEnum.DESCRIPTION.name(), document.getContent());
        variables.put(ProcessVariableEnum.ASSIGNEE.name(), root.getId());
        if (project.getScope() == null){
            variables.put(ProjectProcessVariableEnum.SCOPE.name(), project.getScope());
        }
        variables.put(ProjectProcessVariableEnum.DOCUMENT_TYPE.name(), project.getName());

        runtimeTaskUtil.startProcessInstance(ProcessDefinitionKeyEnum.CREATE_SUBJECT_PROJECT.name(), null,
                user.getId(), variables);
    }
}
